<?php
/**
  * Musashi - A project manager for music groups and bands
  * Copyright (C) 2010 Daniel Torres
  *
  * This program is free software: you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
  * the Free Software Foundation, either version 3 of the License, or
  * (at your option) any later version.
  *
  * This program is distributed in the hope that it will be useful,
  * but WITHOUT ANY WARRANTY; without even the implied warranty of
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  * GNU General Public License for more details.
  *
  * You should have received a copy of the GNU General Public License
  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
  *
  */

/**
 *  Controls actions related to the files dialog
 *  
 * @package com_musashi
 * @author Daniel Torres
 */
 // Make sure we have access to this page
defined('_JEXEC') or die ('Restricted access');

// Controller
jimport('joomla.application.component.controller');

// Make sure this user is a registered one. Otherwise, send him to the registration page
require_once(JPATH_COMPONENT.DS.'models'.DS.'user.php');

class MusashiControllerFiles extends JController
{

    
    /**
     *  Makes sure this operation is valid by checking the validFormCheck flag.
     *  The flag is automatically reset upon call.
     */
    function isValidForm()
    {
        $session =& JFactory::getSession();
        $result = $session->get('validFormCheck',false);
        $session->set('validFormCheck',false);
        
        return $result;
    }
    

    /**
     * Displays the main Costumes view
     * @access public
     */
    function display()
    {
        // Make sure we're registered  users
        if( MusashiModelUser::validateUser( 'http://'.$_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"] ) == false )
        {
            // Redirect to registration view
            $url = MusashiModelUser::getUnregisteredUserPath();
            $this->setRedirect( $url );            
        }
        
        
        parent::display();
    }
    
    /**
     *  Adds a new folder to the system
     */
    function addFolder()
    {
        $model =& $this->getModel('files');        
        $name  = JRequest::getString('name');
        $desc  = JRequest::getString('description');
        $route = JRoute::_('index.php?option=com_musashi&controller=files&view=files',false);
        
        if( $model->addFolder($name,$desc))
        {
            // Get the resulting ID of this folder, and select it as the default
            $newID = $model->getFolderID($name);
            $route = JRoute::_('index.php?option=com_musashi&controller=files&view=files&fid='.$newID,false);
        }
        else
        {
            $session =& JFactory::getSession();
            $session->set('errorMessage','Failed to update information!');
        }
                        
        $this->setRedirect($route);
    }
    
    /**
     *  Attempts to delete a folder
     *  This will only work if the folder itself is empty
     */
    function delFolder()
    {
        $model =& $this->getModel('files');
        $fid   = JRequest::getInt('fid');
        
        if( $model->deleteFolder($fid) == false)
        {
            $session =& JFactory::getSession();
            $session->set('errorMessage','Failed to update delete folder!');            
        }
        
        $this->setRedirect( JRoute::_('index.php?option=com_musashi&controller=files&view=files',false));
    }
    
    /**
     *  Returns a descriptive string for a file upload error message. This
     *  information comes from PHP documentation, and might change on newer
     *  versions.
     *  @param a_nErrorCode An error parameter obtained from the $_FILE array
     *  @return A string description of the problem
     */
    function getFileErrorMsg( $a_nErrorCode )
    {
        switch ($a_nErrorCode)
        { 
        case UPLOAD_ERR_INI_SIZE: 
            return 'Maximum filesize limit exceeded'; 
        case UPLOAD_ERR_FORM_SIZE: 
            return 'Maximum filesize limit exceeded'; 
        case UPLOAD_ERR_PARTIAL: 
            return 'Failed to upload all data'; 
        case UPLOAD_ERR_NO_FILE: 
            return 'No file was uploaded'; 
        case UPLOAD_ERR_NO_TMP_DIR: 
            return 'Missing a temporary folder'; 
        case UPLOAD_ERR_CANT_WRITE: 
            return 'Failed to write file to disk'; 
        case UPLOAD_ERR_EXTENSION: 
            return 'File upload stopped by extension'; 
        default: 
            return 'Unknown upload error'; 
        }         
    }
    
    
    /**
     *  Makes sure our file folder is created and can be used
     */
    function verifyUserFolder()
    {
        // Create the complete path
        $fullPath = $this->getModel('files')->getUploadPath();
        
        // Verify that the path exists
        if( !is_dir($fullPath) )
        {
            if(mkdir($fullPath))
            {
                return chmod($fullPath,0777);
            }
            return false;
        }
        // Verify that we have access
        else
        {
            $stats = substr(sprintf('%o',fileperms($fullPath)),-4);
            if( $stats != 0777)
            {
                return chmod($fullPath,0777);
            }
            
            return true;            
        }
        
    }
    
    
    /**
     *  Adds a file
     */
    function addFile()
    {
        $model   =& $this->getModel('files');
        $session =& JFactory::getSession();
        $folder  =  JRequest::getInt('folderID');
        
        // Make sure we have a place to write this file into
        if( $this->verifyUserFolder() )
        {
            // 1. Was there any upload problem?
            $status = $_FILES['userfile']['error'];
            if( $status != 0 )
            {
                $errorStr = $this->getFileErrorMsg($status);
                $session->set('errorMessage','Error: '.$errorStr);                
            }
            else
            {
                // Get the specified name for this file
                $filename   = $_FILES['userfile']['name'];
                
                // Register this file and get a storage name for it
                $fileID = $model->registerFile( $folder, $filename, JRequest::getString('description'));
                
                if ($fileID)
                {
                    // Get the physical name for this file
                    $uploadPath = $model->getPhysicalFilename( $fileID );
                    
                    if( $uploadPath )
                    {
                        // Attempt to redirect the file to its new location                                
                        if( move_uploaded_file($_FILES['userfile']['tmp_name'], $uploadPath) == true )
                        {
                            // ... Nothing at the moment. We succeeded
                            
                        }
                        else
                        {
                            // Roll-back this change
                            $model->deleteFile( $fileID );
                            $session->set('errorMessage','Error: Failed to register file');
                        }                        
                    }
                    else
                    {
                        $session->set('errorMessage','Error: Failed to add the file to Musashi database');
                    }
                }
                else
                {
                    $session->set('errorMessage','Error: Failed to register file');
                }
            }            
        }
        else
        {
            $session->set('errorMessage','Error: Failed to upload file due to writing permissions. Contact administrator');
        }
        
        //$arrayStr = print_r($_FILES,true);
        //$session->set('actionResult',$arrayStr);
    }
    
    /**
     *  Deletes a given file
     */
    function delFile()
    {
        $model   =& $this->getModel('files');
        $session =& JFactory::getSession();
        $folder  = JRequest::getInt('fid');
        $file    = JRequest::getInt('file');
        
        // Proceed to delete the file
        if( $model->deleteFile($file) != true)
        {
            $session->set('actionResult','Error: Failed to delete file');
        }
        
        $route = JRoute::_('index.php?option=com_musashi&controller=files&view=files&fid='.$folder, false);
        $this->setRedirect($route);
   
    }


    /**
     *    Causes you to download a file
     */
    function download()
    {
        $model   =& $this->getModel('files');
        $session =& JFactory::getSession();
        $folder  = JRequest::getInt('fid');
        $file    = JRequest::getInt('file');
        
        // Delegate to the model
        $model->downloadFile($file);
        $route = JRoute::_('index.php?option=com_musashi&controller=files&view=files&fid='.$folder);
        $this->setRedirect($route);
     
    }
    
}

?>